import React, {useRef} from 'react';
import {UploadOutlined} from '@ant-design/icons';
import {Button, message, Upload} from 'antd';
import type {ProFormInstance} from '@ant-design/pro-form';
import ProForm, { ProFormSelect, ProFormText,} from '@ant-design/pro-form';
import {useRequest} from 'umi';
import {editUser, queryCurrent} from '../service';

import type {UploadProps} from "antd/es";
import ImgCrop from "antd-img-crop";
import {Toast} from "antd-mobile";
import {useEmotionCss} from "@ant-design/use-emotion-css";

const BaseView: React.FC = () => {
  // 获取用户基本信息
  const { data: currentUser, loading } = useRequest(() => {
    return queryCurrent();
  });

  // 获取用户头像
  const getAvatarURL = () => {
    if (currentUser) {
      if (currentUser.avatar) {
        return currentUser.avatar;
      }
      return 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
    }
    return '';
  };
  // Form更新入口
  const formRef = useRef<ProFormInstance>();

  // 头像上传
  const token = localStorage.getItem('token');
  const props: UploadProps = {

    name: 'file',
    action: '/api/upload?path=avatar',
    headers: {
      Authorization: `Bearer ${token}`,
    },
    onChange(info) {
      if (info.file.status === 'done') {

        // 上传动作已经完成
        if (info.file.response?.status === 'done') {
          formRef?.current?.setFieldsValue({
            avatar: info.file.response.path    // 可以绑定后台返回的path，或者fid，根据需求，取对应的数据
          })
          message.success('头像上传成功，请点下方提交保存更新（不提交不生效）！');
        } else {
          message.error(`${info.file.name} 上传失败！`);
        }
      }
    },

    // 上传进度条
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: percent => percent && `${parseFloat(percent.toFixed(2))}%`,
    },
  };
  // css in js
  const baseViewStyle = useEmotionCss(()=>{
    return {
      flexDirection: 'column-reverse',
    }
  })
  const avatarTitleStyle = useEmotionCss(()=>{
    return {
      height: '22px',
      marginBottom: '8px',
      lineHeight: '22px',
    }
  })
  const avatarStyle = useEmotionCss(()=>{
    return {
      height: '120px',
      width: '120px',
      paddingLeft: '28px',
      marginBottom: '12px',
      overflow: 'hidden',
      img: {
        width: '100%',
      }
    }
  })
  const buttonViewStyle = useEmotionCss(()=>{
    return {
      paddingTop: '25px',
      height: '60px',
      marginBottom: '12px',
      overflow: 'hidden',
      img: {
        width: '100%',
      }
    }
  })
  const leftStyle = useEmotionCss(()=>{
    return {
      minHeight: '448px',
      minWidth: '224px',
    }
  })
  const rightStyle = useEmotionCss(()=>{
    return {
      flex: '1',
    }
  })

  // 头像组件 方便以后独立，增加裁剪之类的功能
  const AvatarView = ({ avatar }: { avatar: string }) => (
    <>
      <div className={avatarTitleStyle}>头像</div>
      <div style={{width: `100%`, display: 'flex'}}>
        <div style={{width: `50%`}}>
          <div className={avatarStyle}>
            <img src={avatar} alt="avatar"/>
          </div>
        </div>
        <div style={{width: `50%`}}>
          <ImgCrop>
            <Upload {...props} showUploadList={false}>
              <div className={buttonViewStyle}>
                <Button>
                  <UploadOutlined/>
                  更换头像
                </Button>
              </div>
            </Upload>
          </ImgCrop>
        </div>
      </div>
    </>
  );

  // 保存用户修改的数据
  const handleFinish = async (fields: any) => {
    try {
      const res = await editUser({...fields});
      if (res && res.status === "done") {
        Toast.show({
          content: res.message,
          icon: "success"
        })
        return true;
      } else {
        Toast.show({
          content: res.message,
          icon: "fail"
        })
        return false;
      }
    } catch (error) {
      Toast.show({
        content: "保存失败！请重试。。。",
        icon: "fail"
      })
      return false;
    }
  };

  return (
    <div className={baseViewStyle}>
      {loading ? null : (
        <>
          <div className={leftStyle}>
            <ProForm
              formRef={formRef}
              layout="vertical"
              onFinish={handleFinish}
              submitter={{
                resetButtonProps: {
                  style: {
                    display: 'none',
                  },
                },
                submitButtonProps: {
                  children: '更新基本信息',
                  size: "large",
                  style: {
                    width: `100%`
                  }
                },
              }}
              initialValues={{
                ...currentUser,
              }}
            >
              <ProFormText
                name="username"
                label="账号"
                fieldProps={{
                  size: 'large',
                }}
                disabled={true}
              />
              <ProFormText
                name="nickName"
                label="姓名"
                fieldProps={{
                  size: 'large',
                }}
                rules={[
                  {
                    required: true,
                    message: '请输入您的昵称!',
                  },
                ]}
              />
              <ProFormSelect
                name="gender"
                label={"性别"}
                fieldProps={{
                  size: 'large',
                }}
                options={[
                  {value: 0, label: "女"},
                  {value: 1, label: "男"},
                  {value: 2, label: "未知"},
                ]}
                rules={[{required: true, message: '性别是必选项',},]}
              />
              <ProFormText
                name="email"
                label="邮箱"
                fieldProps={{
                  size: 'large',
                }}
                rules={[
                  {
                    required: true,
                    message: '请输入您的邮箱!',
                  },
                ]}
              />
              <ProFormText
                name="mobile"
                fieldProps={{
                  size: 'large',
                }}
                label="手机号码"
                rules={[
                  {
                    pattern: /^((13\d)|(14[5,7])|(15[^4,\\D])|(17[0,1,3,6-8])|(18\d)|(19[8,9])|(166))\d{8}$/,
                    message: '手机号码格式不正确！'
                  }
                ]}
              />
              <ProFormText name="avatar" width="md" hidden={true}/>
              <div className={rightStyle}>
                <AvatarView avatar={getAvatarURL()}/>
              </div>
            </ProForm>
          </div>
        </>
      )}
    </div>
  );
};

export default BaseView;
